const App = getApp();
var config = require('../../../../script/config.js')
import Uploader from 'miniprogram-file-uploader';
const recorderManager = wx.getRecorderManager();
const innerAudioContext = wx.createInnerAudioContext();
let countdownInterval = null;
let waveInterval = null;
let wavePlayInterval = null;
Component({
  options: {
    addGlobalClass: true,
  },
  /**
   * 组件的属性列表
   */
  properties: {
    orderInfo: {
      type: Object,
      value: null
    },
  },
  observers: {
    'orderInfo': function (val) {
      if (val != null) {
        this.setData({
          required: val.NeedFile && val.NeedFile === 1
        })
        this.getOrderFiles(val);
      }
    }
  },
  lifetimes: {
    created: function () {
      const _this = this;
      wx.getLocation({
        type: 'gcj02',
        success(res) {
          const latitude = res.latitude;
          const longitude = res.longitude;
          wx.request({
            method: 'GET',
            url: `https://restapi.amap.com/v3/geocode/regeo?output=json&location=${longitude},${latitude}&key=${config.amapKey}&radius=100&extensions=all`,
            success: function (res) {
              if (res.data.status === '1') {
                _this.setData({
                  areaSelectedStr: res.data.regeocode.formatted_address
                });
              }
            },
          })
        }
      })
    },
    attached: function () {},
    ready: function () {
      this.getUserInfo()
      recorderManager.onStop((res) => {
        console.log('stop')
        clearInterval(countdownInterval);
        countdownInterval = null;
        clearInterval(waveInterval);
        waveInterval = null;
        const recordFilePath = [...this.data.recordFilePath];
        const noUploadRecordList = [...this.data.noUploadRecordList];
        const record = {
          tempFilePath: res.tempFilePath,
          duration: res.duration,
          fileSize: res.fileSize,
        }
        recordFilePath.push(record);
        noUploadRecordList.push(record);
        this.setData({
          recordFilePath,
          noUploadRecordList,
          countdown: 0
        });
        // console.log('录音文件路径:', list);
      });
      innerAudioContext.onEnded(() => {
        this.setData({
          recordPlayShow: false
        });
        clearInterval(wavePlayInterval);
        wavePlayInterval = null;
      })
    },
    detached: function () {
      clearInterval(countdownInterval);
      countdownInterval = null;
      clearInterval(waveInterval);
      waveInterval = null;
      clearInterval(wavePlayInterval);
      wavePlayInterval = null;
      recorderManager.stop();
      // if (innerAudioContext) {
      //   innerAudioContext.destroy();
      // }
    }
  },
  pageLifetimes: {

  },
  /**
   * 组件的初始数据
   */
  data: {
    userinfo: null,
    required: true,
    baseUrl: config.baseUrl,
    itemList: ['图片', '视频'],
    sourceType: ['拍摄', '相册', '拍摄或相册'],
    imgList: [], // 显示的图片列表
    imgFileList: [], // 上传的图片文件列表
    videoFileList: [], // 上传的视频文件列表
    watermarkWidth: 0,
    waterMarkHeight: 0,
    areaSelectedStr: '地理位置',
    isRecording: false,
    countdown: 0, // 倒计时秒数
    recordFilePath: [], // 录音文件路径 -- 已经录音的
    noUploadRecordList: [], // 没上传的录音文件列表
    uploadRecordList: [], // 已上传的录音文件列表
    maxDuration: 60, // 最大录音时长（秒）
    waveHeight: [20, 30, 25, 40, 35, 28, 32, 37, 40, 48],
    recordPlayShow: false,
    wavePlayHeight: [10, 18, 24, 20, 16, 22],
    isPlaying: false
  },

  /**
   * 组件的方法列表
   */
  methods: {
    getUserInfo: function () {
      try {
        var value = wx.getStorageSync(config.storageKey.userinfo);
        if (value) {
          this.setData({
            userinfo: value
          })
        }
      } catch (e) {
        // Do something when catch error
      }
    },
    // 回显图片视频
    getOrderFiles(data) {
      if (data.MFileList && data.MFileList.length > 0) {
        this.setData({
          videoFileList: data.MFileList
        });
      }
      if (data.VFileList && data.VFileList.length > 0) {
        this.setData({
          uploadRecordList: data.VFileList
        });
      }
      if (data.PFileList && data.PFileList.length > 0) {
        const arr = [];
        for (let i = 0; i < data.PFileList.length; i++) {
          arr.push(this.data.baseUrl + '/' + data.PFileList[i].FilePath)
        }
        this.setData({
          imgFileList: data.PFileList,
          imgList: arr
        });
      }
    },
    chooseVideoImage: function () {
      wx.showActionSheet({
        title: "选择上传类型",
        itemList: ['图片', '视频'],
        success: (res) => {
          if (res.tapIndex == 0) {
            this.chooseImages()
          } else {
            this.chooseVideo()
          }
        }
      })
    },
    chooseImages: function () {
      if (this.data.imgFileList.length >= 5) {
        wx.showToast({
          title: '最多只能上传5张图片！',
          icon: "none",
          duration: 2000
        })
        return
      }
      const _this = this;
      // 上传图片
      wx.chooseImage({
        count: 5 - this.data.imgFileList.length, //默认9
        sizeType: ['original'], //可以指定是原图还是压缩图，默认二者都有
        // mediaType: ['image'],
        sourceType: ['album', 'camera'], //从相册选择
        success: (res) => {
          wx.showLoading({
            mask: true,
            title: '上传中...'
          });
          const tempFiles = res.tempFiles;
          _this.uploadOneByOne(tempFiles, 0, 0, 0, tempFiles.length);
        }
      });
    },
    addWatermark(tempFilePath) {
      const that = this;
      return new Promise((resolve, reject) => {
        // 获取图片信息
        wx.getImageInfo({
          src: tempFilePath,
          success(res) {
            if (res.width <= 0 || res.height <= 0) {
              reject()
            }
            let canvasW = 0;
            let canvasH = 0;
            const c = res.width;
            1280
            const h = res.height;
            1280
            if (c <= 1080 && h <= 1080) {
              canvasW = c;
              canvasH = h;
            } else {
              if (c > h && c > 1080) {
                const scale = 1080 / c
                canvasW = 1080;
                canvasH = h * scale;
              }
              if (h >= c && h > 1080) {
                const scale = 1080 / h
                canvasH = 1080;
                canvasW = c * scale;
              }
            }

            that.setData({
              watermarkWidth: canvasW,
              waterMarkHeight: canvasH
            });
            const ctx = wx.createCanvasContext('watermark', that)
            ctx.drawImage(tempFilePath, 0, 0, canvasW, canvasH)

            let newDate = new Date();
            let year = newDate.getFullYear(); //年
            let month = (newDate.getMonth() + 1) >= 10 ? (newDate.getMonth() + 1) : '0' + (newDate.getMonth() + 1); //月
            let day = newDate.getDate() >= 10 ? newDate.getDate() : '0' + newDate.getDate(); //日
            var hour = newDate.getHours() >= 10 ? newDate.getHours() : '0' + newDate.getHours();
            var minute = newDate.getMinutes() >= 10 ? newDate.getMinutes() : '0' + newDate.getMinutes();
            var second = newDate.getSeconds() >= 10 ? newDate.getSeconds() : '0' + newDate.getSeconds();
            let timestr = '拍摄时间：' + year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
            let address = '拍摄地址：' + that.data.areaSelectedStr;
            let weather = '天气：暂无'
            if (that.data.orderInfo.WeatherInfo) {
              weather = '天气：' + that.data.orderInfo.WeatherInfo.WeatherText + ' ' + that.data.orderInfo.WeatherInfo.Temperature + ' ℃' + ' ' + that.data.orderInfo.WeatherInfo.WindDir;
            }
            // let user = that.data.orderInfo.DeptName + ' ' + that.data.orderInfo.ConsName;
            let user = that.data.userinfo.DEPT_NAME + ' ' + that.data.userinfo.USER_NAME;
            let remark = '备注：' + that.data.orderInfo.Address;

            let fontSize = 26;
            if (canvasW >= 1500) {
              fontSize = 42;
            } else if (canvasW >= 1000) {
              fontSize = 34;
            }


            ctx.setFillStyle('rgba(0,0,0,.3)')
            ctx.fillRect(0, canvasH - fontSize * 10 - 60, canvasW, fontSize * 10 + 60)


            // 设置文字字号及字体
            ctx.setFontSize(fontSize);
            // 设置画笔颜色
            ctx.setFillStyle('transparent');
            // 绘制矩形
            ctx.fillRect(0, 0, canvasW, canvasH);
            // 设置画笔颜色
            ctx.setFillStyle('#ffffff');
            // 填入文字
            let line = 0;
            const diff = fontSize + 10;
            const remarkW = ctx.measureText(remark).width;
            if (remarkW - canvasW + 40 < 0) {
              ctx.fillText(remark, 20, canvasH - 60);
              line += 1;
            } else {
              for (let i = 0; i < remark.length; i++) {
                const w = ctx.measureText(remark.substring(0, i + 1)).width;
                if (w > (canvasW - 40)) {
                  ctx.fillText(remark.substring(0, i), 20, canvasH - (60 + diff));
                  ctx.fillText(remark.substring(i), 20, canvasH - 60);
                  line += 2;
                  break;
                }
              }
            }

            const addressW = ctx.measureText(address).width;
            if (addressW - canvasW + 40 < 0) {
              ctx.fillText(address, 20, canvasH - (60 + line * diff));
              line += 1;
            } else {
              for (let i = 0; i < address.length; i++) {
                const w = ctx.measureText(address.substring(0, i + 1)).width;
                if (w > (canvasW - 40)) {
                  ctx.fillText(address.substring(0, i), 20, canvasH - (60 + (line + 1) * diff));
                  ctx.fillText(address.substring(i), 20, canvasH - (60 + line * diff));
                  line += 2;
                  break;
                }
              }
            }
            ctx.fillText(timestr, 20, canvasH - (60 + line * diff));
            line += 1
            ctx.fillText(weather, 20, canvasH - (60 + line * diff));
            line += 1
            ctx.fillText(user, 20, canvasH - (60 + line * diff));

            // ctx.setFillStyle('rgba(0,0,0,.3)')
            // ctx.fillRect(0, canvasH - (60 + (line + 1) * diff), canvasW, (60 + line * diff))

            // ctx.setLineWidth(2);
            // ctx.setStrokeStyle('#FFF');
            // ctx.moveTo(10, canvasH - (60 + line * diff + fontSize));
            // ctx.lineTo(10, canvasH - 60);
            // ctx.stroke();


            ctx.draw(false, setTimeout(() => {
              wx.canvasToTempFilePath({
                quality: 1,
                fileType: 'jpg',
                canvasId: 'watermark',
                destWidth: canvasW * App.globalData.pixelRatio,
                destHeight: canvasH * App.globalData.pixelRatio,
                width: canvasW,
                height: canvasH,
                success: function (res) {
                  resolve(res.tempFilePath);
                },
                fail: function (res) {
                  reject(res)
                }
              }, that)
            }, 1000));
          },
          fail(err) {
            console.log(err)
          }
        })
      })
    },
    async uploadOneByOne(imgPaths, successUp, failUp, count, length) {
      var that = this;
      const token = wx.getStorageSync(config.storageKey.token)
      const xtoken = wx.getStorageSync(config.storageKey.xtoken)
      const addWatermarkRes = await that.addWatermark(imgPaths[count].path) //先加水印
      if (addWatermarkRes) {
        wx.uploadFile({
          url: config.baseUrl + '/api/Upload/Upload',
          method: "POST",
          header: {
            'Authorization': 'Bearer ' + token,
            'X-Authorization': 'Bearer ' + xtoken
          },
          // filePath: imgPaths[count].path,
          filePath: addWatermarkRes,
          name: 'file',
          timeout: 120000, // 超时时间
          success: (resf) => {
            if (resf.statusCode === 200) {
              const resData = JSON.parse(resf.data);
              if (resData && resData.code === 200) {
                successUp++; //成功+1
                const relData = resData.data;
                const file = {
                  FileName: relData[0],
                  FilePath: relData[0],
                  Size: imgPaths[count].size
                }
                that.setData({
                  // imgList: that.data.imgList.concat(imgPaths[count].path),
                  imgList: that.data.imgList.concat(config.baseUrl + '/' + relData[0]),
                  imgFileList: that.data.imgFileList.concat(file)
                })
              } else {
                failUp++; //失败+1
              }
            } else {
              failUp++; //失败+1
            }
          },
          fail: function (e) {
            failUp++; //失败+1
          },
          complete: function (e) {
            count++; //下一张
            if (count == length) {
              if (successUp > 0) {
                wx.showToast({
                  title: '已上传' + successUp + "张图片",
                  icon: 'success',
                  duration: 2000
                })
              } else {
                wx.showToast({
                  title: "图片上传失败",
                  icon: 'error'
                })
              }
            } else {
              that.uploadOneByOne(imgPaths, successUp, failUp, count, length);
            }
          }
        })
      } else {
        failUp++; //失败+1
        count++; //下一张
        if (count != length) {
          that.uploadOneByOne(imgPaths, successUp, failUp, count, length);
        }
      }
    },
    previewImage: function (e) {
      //预览图片
      const that = this;
      var index = e.currentTarget.dataset.index;
      wx.previewImage({
        current: that.data.imgList[index],
        urls: that.data.imgList
      })
    },
    delect: function (e) {
      var index = e.currentTarget.dataset.index;
      wx.showModal({
        title: "提示",
        content: "是否要删除该图片",
        success: (res) => {
          if (res.confirm) {
            const imgList = [...this.data.imgList]
            const imgFileList = [...this.data.imgFileList]
            imgList.splice(index, 1);
            imgFileList.splice(index, 1);
            this.setData({
              imgList: imgList,
              imgFileList: imgFileList
            })
          }
        }
      })
    },
    chooseVideo: function () {
      const that = this;
      if (that.data.videoFileList.length >= 3) {
        wx.showToast({
          title: '最多只能上传3个视频！',
          icon: "none",
          duration: 2000
        })
        return
      }
      const token = wx.getStorageSync(config.storageKey.token);
      const xtoken = wx.getStorageSync(config.storageKey.xtoken);
      // 上传视频
      wx.chooseMedia({
        count: 1,
        maxDuration: 300,
        compressed: true,
        camera: 'back',
        mediaType: ['video'],
        sourceType: ['album', 'camera'],
        sizeType: ['original', 'compressed'],
        success: (responent) => {
          wx.getVideoInfo({
            src: responent.tempFiles[0].tempFilePath,
            success(res) {
              const isLarge = res.size > 60 * 1024;
              if (isLarge) {
                wx.showToast({
                  title: '单个视频不能大于60MB！',
                  icon: "none"
                });
                return;
              } else {
                wx.showLoading({
                  mask: true,
                  title: '视频上传中...'
                });
                // 分片上传
                if (Uploader.isSupport()) {
                  const uploader = new Uploader({
                    tempFilePath: responent.tempFiles[0].tempFilePath,
                    totalSize: responent.tempFiles[0].size,
                    uploadUrl: config.baseUrl + '/api/Upload/UploadPartFile',
                    mergeUrl: config.baseUrl + '/api/Upload/MergeFile',
                    verifyUrl: config.baseUrl + '/api/Upload/CheckFile',
                    testChunks: true,
                    timeout: 100000,
                    fileName: responent.tempFiles[0].tempFilePath.slice(responent.tempFiles[0].tempFilePath.length - 10),
                    header: {
                      Authorization: 'Bearer ' + token
                      // X-Authorization: 'Bearer ' + xtoken
                    },
                  })
                  uploader.upload();

                  // 文件上传成功
                  uploader.on('success', (res) => {
                    const videoFileList = {
                      FileName: res.url,
                      FilePath: res.url,
                      Size: responent.tempFiles[0].size
                    };
                    that.setData({
                      videoFileList: that.data.videoFileList.concat(videoFileList)
                    })
                    wx.showToast({
                      title: "视频上传成功",
                      icon: 'success',
                      duration: 2000
                    })
                  })

                  // 文件上传失败
                  uploader.on('fail', (res) => {
                    wx.showToast({
                      title: '视频上传失败！',
                      duration: 2000
                    });
                  })
                }
              }
            },
            fail(err) {
              console.log(err)
            }
          })
        }
      })
    },
    delectVideo: function (e) {
      const that = this;
      var index = e.currentTarget.dataset.index;
      wx.showModal({
        title: "提示",
        content: "是否要删除此视频",
        success: (res) => {
          if (res.confirm) {
            const videoFileList = [...that.data.videoFileList]
            videoFileList.splice(index, 1);
            that.setData({
              videoFileList: videoFileList
            })
          }
        }
      })
    },
    /*************  语音录入 ***********/
    // 开始录音
    startRecording() {
      if ((this.data.noUploadRecordList.length + this.data.uploadRecordList.length) >= 3) {
        wx.showToast({
          title: '最多可录3条语音！',
          icon: "none",
          duration: 2000
        })
        return
      }
      this.checkPermission(() => {
        this.setData({
          isRecording: true,
          // countdown: this.data.maxDuration
          countdown: 0
        });

        // 启动倒计时
        countdownInterval = setInterval(() => {
          const newCount = this.data.countdown + 1;
          this.setData({
            countdown: newCount
          });
          if (newCount >= this.data.maxDuration) {
            this.stopRecording();
            wx.showToast({
              title: '已达最大时长',
              icon: 'none'
            });
          }
        }, 1000);

        // 启动波形动画
        waveInterval = setInterval(() => {
          const waveHeight = [...this.data.waveHeight];
          const arr = waveHeight.map(() => {
            return Math.floor(Math.random() * 30) + 20
          });
          this.setData({
            waveHeight: arr
          })
        }, 200)

        // 配置录音参数
        recorderManager.start({
          duration: this.data.maxDuration * 1000,
          format: 'mp3',
          sampleRate: 16000,
          numberOfChannels: 1
        });
      });
    },
    // 停止录音
    stopRecording() {
      if (!this.data.isRecording) return;
      this.setData({
        isRecording: false,
      });
      recorderManager.stop();
    },
    playRecording(e) {
      this.setData({
        recordPlayShow: true,
        isPlaying: true
      })
      this.setPlayingInterval();

      let url = e.currentTarget.dataset.url;
      let type = e.currentTarget.dataset.type;
      if (type === 'upload') {
        url = this.data.baseUrl + '/' + url
      }
      innerAudioContext.src = url;
      innerAudioContext.play();
    },
    setPlayingInterval() {
      wavePlayInterval = setInterval(() => {
        const waveHeight = [...this.data.wavePlayHeight];
        const arr = waveHeight.map(() => {
          return Math.floor(Math.random() * 10) + 15
        });
        this.setData({
          wavePlayHeight: arr
        })
      }, 200)
    },
    playControl() {
      if (!innerAudioContext) return
      if (this.data.isPlaying) {
        clearInterval(wavePlayInterval);
        wavePlayInterval = null;
        innerAudioContext.pause();
      } else {
        this.setPlayingInterval();
        innerAudioContext.play();
      }
      this.setData({
        isPlaying: !this.data.isPlaying
      });
    },
    closePlaying() {
      innerAudioContext.stop();
      clearInterval(wavePlayInterval);
      wavePlayInterval = null;
      this.setData({
        recordPlayShow: false,
        isPlaying: false
      });
    },
    deleteRecordingNoUpload(e) {
      const filePath = e.currentTarget.dataset.url;
      const arr = [...this.data.recordFilePath].filter(item => {
        return item.tempFilePath !== filePath
      })
      this.setData({
        recordFilePath: arr
      });
      if (this.data.isPlaying) {
        this.closePlaying();
      }
    },
    deleteRecordingUpdate(e) {
      const filePath = e.currentTarget.dataset.url;
      const arr = [...this.data.uploadRecordList].filter(item => {
        return item.FilePath !== filePath
      })
      this.setData({
        uploadRecordList: arr
      });
      if (this.data.isPlaying) {
        this.closePlaying();
      }
    },
    uploadRecord() {
      if (this.data.recordFilePath.length === 0) {
        wx.showToast({
          title: '请先录入语音！',
          icon: "none",
          duration: 2000
        })
        return;
      }
      this.uploadRecordOneByOne(this.data.recordFilePath, 0, 0, 0, this.data.recordFilePath.length);
    },
    uploadRecordOneByOne(records, successUp, failUp, count, length) {
      var that = this;
      const token = wx.getStorageSync(config.storageKey.token)
      const xtoken = wx.getStorageSync(config.storageKey.xtoken)
      wx.uploadFile({
        url: config.baseUrl + '/api/Upload/Upload',
        method: "POST",
        header: {
          'Authorization': 'Bearer ' + token,
          'X-Authorization': 'Bearer ' + xtoken
        },
        filePath: records[count].tempFilePath,
        name: 'file',
        timeout: 120000, // 超时时间
        success: (resf) => {
          if (resf.statusCode === 200) {
            const resData = JSON.parse(resf.data);
            if (resData && resData.code === 200) {
              successUp++; //成功+1
              const relData = resData.data;
              const file = {
                FileName: relData[0],
                FilePath: relData[0],
                Size: records[count].duration
              }
              const noUploadRecordList = JSON.parse(JSON.stringify(that.data.noUploadRecordList));
              const index = noUploadRecordList.findIndex(m => m.tempFilePath === records[count].tempFilePath);
              noUploadRecordList.splice(index, 1);
              that.setData({
                uploadRecordList: that.data.uploadRecordList.concat(file),
                noUploadRecordList
              });
            } else {
              failUp++; //失败+1
            }
          } else {
            failUp++; //失败+1
          }
        },
        fail: function (e) {
          failUp++; //失败+1
        },
        complete: function (e) {
          count++; //下一张
          if (count == length) {
            if (successUp > 0) {
              wx.showToast({
                title: '已上传' + successUp + "条音频",
                icon: 'success',
                duration: 2000
              });
              const noUploadRecordList = JSON.parse(JSON.stringify(that.data.noUploadRecordList));
              that.setData({
                recordFilePath: noUploadRecordList
              });
            } else {
              wx.showToast({
                title: "音频上传失败",
                icon: 'error'
              })
            }
          } else {
            that.uploadRecordOneByOne(records, successUp, failUp, count, length);
          }
        }
      })
    },
    // 权限检查
    checkPermission(callback) {
      wx.getSetting({
        success: (res) => {
          if (res.authSetting['scope.record']) {
            callback();
          } else {
            wx.authorize({
              scope: 'scope.record',
              success: callback,
              fail: () => {
                wx.showModal({
                  title: '权限提示',
                  content: '请在设置中开启录音权限',
                  success: (res) => {
                    if (res.confirm) wx.openSetting();
                  }
                });
              }
            });
          }
        }
      });
    },
    /*************  语音录入 ***********/
    getSubmitData() {
      const mergedArray = this.data.imgFileList.concat(this.data.videoFileList, this.data.uploadRecordList);
      return {
        files: mergedArray,
        allUpload: this.data.noUploadRecordList.length === 0
        // imgFileList: this.data.imgFileList,
        // videoFileList: this.data.videoFileList,
        // uploadRecordList: this.data.uploadRecordList
      }
    },
  }
})